<script setup>
import { ref, onMounted } from 'vue';
import { orderPageService } from '@/api/order';
import { useRouter } from 'vue-router'

// 路由
const router = useRouter()

// 日期选择器数据
const dateTiem = ref([])

// 日期快捷键
const shortcuts = [
    {
        text: '上周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)
            return [start, end]
        },
    },
    {
        text: '上个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            return [start, end]
        },
    },
    {
        text: '上3个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 3)
            return [start, end]
        },
    },
]

// 数据
const tableData = ref([]);

// 搜索表单数据
const search = ref({});

// 分页
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(10);
// 总数
const total = ref(0);

onMounted(() => {
    // 初始化数据
    handleSearch();
})

// 分页查询
const handleSearch = async () => {
    console.log('请求参数:', search.value);
    const result = await orderPageService(search.value);
    tableData.value = result.data.list;
    total.value = parseInt(result.data.total);
};

// 清空搜索选择
const clearSearch = () => {
    currentPage.value = 1;
    pageSize.value = 10;
    dateTiem.value = []
    search.value = {};
    handleSearch();
}

// 每页展示记录数变化
const handleSizeChange = (val) => {
    // 同步更新 pageSize
    pageSize.value = val;
    // 同步更新搜索参数
    search.value.pageSize = val;
    console.log(`每页 ${val} 条`);
    handleSearch();
}
// 页码变化时触发
const handleCurrentChange = (val) => {
    // 同步更新 currentPage
    currentPage.value = val;
    // 同步更新搜索参数
    search.value.pageNum = val;
    console.log(`当前页: ${val}`);
    handleSearch();
}

// 跳转至详情
const handleView = (index, row) => {
    console.log(row);
    // 查看订单逻辑
    router.push(`/admin/order/info/${row.id}`)
};

const handleShip = (index, row) => {
    // 订单发货逻辑
};

const handleTrack = (index, row) => {
    // 订单跟踪逻辑
};

const handleDelete = (index, row) => {
    // 删除订单逻辑
};

// 支付方式格式化
const getPaymentType = (type) => {
    const paymentTypes = ['', '支付宝', '微信', '扣减余额'];
    return paymentTypes[type] || '';
};

// 支付方式对应的 el-tag 类型
const getPaymentTagType = (type) => {
    const tagTypes = ['', 'primary', 'success', 'warning']; // 1:支付宝, 2:微信, 3:扣减余额
    return tagTypes[type] || '';
};

// 订单状态格式化
const getOrderStatus = (status) => {
    const orderStatuses = ['', '未支付', '已付款,未发货', '已发货,未收货', '确认收货，交易成功', '交易取消，订单关闭', '交易结束，未评价', '交易结束，已评价'];
    return orderStatuses[status] || '';
};

// 订单状态对应的 el-tag 类型
const getStatusTagType = (status) => {
    const tagTypes = [
        '',          // 0: 空
        'info',      // 1: 未支付 (灰色)
        'primary',   // 2: 已付款,未发货 (蓝色)
        'warning',   // 3: 已发货,未确认 (黄色)
        'success',   // 4: 确认收货，交易成功 (绿色)
        'danger',    // 5: 交易取消，订单关闭 (红色)
        ''           // 6: 交易结束，已评价 (默认)
    ];
    return tagTypes[status] || '';
};

// 日期时间变化
const handleDateTimeChange = (value) => {
    console.log('时间范围已改变:', value);
    // 可以在这里执行其他逻辑，例如自动搜索等
    if (value && value.length === 2) {
        search.value.createDateTimeStart = value[0];
        search.value.createDateTimeEnd = value[1];
    } else {
        search.value.createDateTimeStart = '';
        search.value.createDateTimeEnd = '';
    }
};

// 价格校验方法
const filterNumberInput = (field) => {
    const value = search.value[field];
    // 移除非数字字符，保留数字和小数点
    const filteredValue = value.replace(/[^0-9.]/g, '');

    // 防止连续小数点和负数
    if (filteredValue === '' || isNaN(filteredValue)) {
        search.value[field] = '';
        return;
    }

    // 限制只能输入一个小数点
    const parts = filteredValue.split('.');
    if (parts.length > 2) {
        search.value[field] = parts[0] + '.' + parts.slice(1).join('');
        return;
    }

    // 自动保留两位小数（可选）
    if (parts[1]?.length > 2) {
        search.value[field] = parseFloat(filteredValue).toFixed(2);
        return;
    }

    // 更新值
    search.value[field] = filteredValue;
}


</script>



<template>
    <div class="form-container">
        <!-- 筛选搜索 -->
        <el-form :inline="true" class="demo-form-inline">
            <el-row class="search-form-row1" :gutter="20">
                <el-col :span="5">
                    <el-form-item label="输入搜索：">
                        <el-input v-model="search.orderNumber" placeholder="订单编号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="收货人：">
                        <!-- <el-input v-model="search.userId" placeholder="收货人姓名/手机号码" clearable></el-input> -->
                        <el-input v-model="search.userId" placeholder="收货人id" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item style="width: 100%;" label="订单状态：">
                        <el-select v-model="search.status" placeholder="全部" style="width: 100%;">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="未支付" value="1"></el-option>
                            <el-option label="已付款,未发货" value="2"></el-option>
                            <el-option label="已发货,未确认" value="3"></el-option>
                            <el-option label="确认收货，交易成功" value="4"></el-option>
                            <el-option label="交易取消，订单关闭" value="5"></el-option>
                            <el-option label="交易结束，已评价" value="6"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item style="width: 100%;" label="订单来源：">
                        <el-select v-model="search.sourceType" placeholder="全部" style="width: 100%;">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="网页订单" value="0"></el-option>
                            <el-option label="APP订单" value="1"></el-option>
                            <el-option label="小程序订单" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第二行 -->
            <el-row class="search-form-row2" :gutter="20">
                <el-col :span="9">
                    <el-form-item label="提交时间范围：">
                        <el-date-picker value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" v-model="dateTiem"
                            type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="开始时间"
                            end-placeholder="结束时间" @change="handleDateTimeChange" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="价格区间">
                        <el-input v-model="search.minPrice" type="number" placeholder="最小价格"
                            @input="filterNumberInput('minPrice')" class="search-small-item" />
                        <span style="margin: 0 1vh 0 1vh;">~</span>
                        <el-input v-model="search.maxPrice" type="number" placeholder="最大价格"
                            @input="filterNumberInput('maxPrice')" class="search-small-item" />
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item>
                        <el-button type="info" @click="clearSearch">清空</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">查询搜索</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 数据列表 -->
        <el-table :data="tableData" style="width: 96%">
            <el-table-column align="center" prop="id" label="编号" width="80"></el-table-column>
            <el-table-column align="center" prop="orderNumber" label="订单编号"></el-table-column>
            <el-table-column align="center" prop="createDateTime" label="提交时间"></el-table-column>
            <el-table-column align="center" prop="userId" label="用户账号"></el-table-column>
            <el-table-column align="center" prop="totalPrice" label="订单金额"></el-table-column>
            <el-table-column align="center" prop="paymentType" label="支付方式">
                <template #default="scope">
                    <el-tag :type="getPaymentTagType(scope.row.paymentType)" effect="light">
                        {{ getPaymentType(scope.row.paymentType) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="sourceType" label="订单来源">
                <template #default="scope">
                    <span v-if="scope.row.sourceType == 0">网页订单</span>
                    <span v-else-if="scope.row.sourceType == 1">APP订单</span>
                    <span v-else>小程序订单</span>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="订单状态">
                <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)" effect="plain">
                        {{ getOrderStatus(scope.row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleView(scope.$index, scope.row)">查看订单</el-button>
                    <el-button v-if="scope.row.status === '待发货'" size="small"
                        @click="handleShip(scope.$index, scope.row)">订单发货</el-button>
                    <el-button v-if="['已完成', '已关闭'].includes(scope.row.status)" size="small"
                        @click="handleTrack(scope.$index, scope.row)">订单跟踪</el-button>
                    <el-button v-if="['未支付', '已关闭'].includes(scope.row.status)" size="small" type="danger"
                        @click="handleDelete(scope.$index, scope.row)">删除订单</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 25, 50, 75, 100, 150, 200]" size="default" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
</template>



<style scoped>
.form-container {
    display: flex;
    flex-direction: column;
    /* 水平居中*/
    align-items: center;
    /* 垂直居中*/
    justify-content: center;
    width: 100%
}

/* 表单位置 */
.demo-form-inline {
    padding: 0 0 0 0;
    width: 100%;
}

/* 搜索表单第一行 */
.search-form-row1 { 
    width: 100%;
    margin: 0 0 0 7% !important;
}

/* 搜索表单第二行 */
.search-form-row2 {
    width: 100%;
    margin: 0 0 0 10% !important;
}



/* 表格位置 */
.el-table {
    margin: 0 0 1vh 0;
}

/* 分页器位置 */
.el-pagination {
    margin: 1vh 0 0 0;
}

/* 输入框宽度 */
.search-small-item {
    width: 100px;
}
</style>
